using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lang.Avalonia.Analysis;

public static class LanguageCodeGenerator
{
    public static string GenerateLanguageConstants(Dictionary<string, Dictionary<string, string>> allResources)
    {
        if (!allResources.Any())
            return string.Empty;

        var stringBuilder = new StringBuilder();

        // 添加文件头注释
        stringBuilder.AppendLine("//------------------------------------------------------------------------------");
        stringBuilder.AppendLine("// <auto-generated>");
        stringBuilder.AppendLine("//     This code was generated by Lang.Avalonia.Analysis.");
        stringBuilder.AppendLine("//     Changes to this file may cause incorrect behavior and will be lost if");
        stringBuilder.AppendLine("//     the code is regenerated.");
        stringBuilder.AppendLine("// </auto-generated>");
        stringBuilder.AppendLine("//------------------------------------------------------------------------------");
        stringBuilder.AppendLine();

        // 使用第一个culture的资源来分析结构
        var firstCultureResources = allResources.Values.First();
        var classStructure = AnalyzeResourceStructure(firstCultureResources.Keys);

        // 生成命名空间
        foreach (var namespaceGroup in classStructure)
        {
            var namespaceName = namespaceGroup.Key;
            var classes = namespaceGroup.Value;

            stringBuilder.AppendLine($"namespace {namespaceName}");
            stringBuilder.AppendLine("{");

            // 生成类
            foreach (var classGroup in classes)
            {
                var className = classGroup.Key;
                var properties = classGroup.Value;

                stringBuilder.AppendLine($"    public static class {className}");
                stringBuilder.AppendLine("    {");

                // 生成属性
                foreach (var property in properties.OrderBy(p => p))
                {
                    var sanitizedPropertyName = SanitizeName(property);
                    var fullKey = $"{namespaceName}.{className}.{sanitizedPropertyName}";
                    stringBuilder.AppendLine($"        public static readonly string {sanitizedPropertyName} = \"{fullKey}\";");
                }

                stringBuilder.AppendLine("    }");
                stringBuilder.AppendLine();
            }

            stringBuilder.AppendLine("}");
            stringBuilder.AppendLine();
        }

        return stringBuilder.ToString();
    }

    private static Dictionary<string, Dictionary<string, List<string>>> AnalyzeResourceStructure(IEnumerable<string> resourceKeys)
    {
        var result = new Dictionary<string, Dictionary<string, List<string>>>();

        foreach (var key in resourceKeys)
        {
            var parts = key.Split('.');
            if (parts.Length < 3) continue; // 至少需要 namespace.class.property

            // 找到根命名空间（通常是最长的公共前缀）
            var namespacePart = parts[0];
            var modulePart = parts[1];
            var classPart = parts[2];
            var propertyPart = string.Join(".", parts.Skip(3));

            if (string.IsNullOrEmpty(propertyPart))
                propertyPart = classPart;

            var fullNamespace = $"{namespacePart}.{modulePart}";

            if (!result.ContainsKey(fullNamespace))
                result[fullNamespace] = new Dictionary<string, List<string>>();

            if (!result[fullNamespace].ContainsKey(classPart))
                result[fullNamespace][classPart] = new List<string>();

            result[fullNamespace][classPart].Add(propertyPart);
        }

        return result;
    }

    private static string SanitizeName(string name)
    {
        if (string.IsNullOrEmpty(name))
            return "Unnamed";

        // 移除或替换无效字符
        var sanitized = new string(name.Where(c => char.IsLetterOrDigit(c) || c == '_').ToArray());

        // 确保不以数字开头
        if (sanitized.Length > 0 && char.IsDigit(sanitized[0]))
            sanitized = "_" + sanitized;

        return sanitized.Length == 0 ? "Unnamed" : sanitized;
    }

    public static string GenerateUsings()
    {
        return @"using System;
";
    }
}